<?php

namespace app\admin\controller\shopro\wallet;

use app\admin\controller\shopro\Common;
use app\admin\model\Admin;
use app\admin\model\shopro\user\WalletLog as WalletLogModel;
use addons\shopro\library\Operator;
use app\admin\model\User;

class ReturnGoods extends Common
{
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new WalletLogModel;
    }
    /**
     * 退单记录
     */
    public function index($id="")
    {
        if (false === $this->request->isPost()) {
            $exportConfig = (new \addons\shopro\library\Export())->getConfig();
            $this->assignconfig("save_type", $exportConfig['save_type'] ?? 'download');
            return $this->view->fetch();
        }
        $walletLogs = WalletLogModel::with("user");
        $list_rows = $this->request->param('list_rows', 10);

        $search = $this->request->param("search");
        $search=json_decode($search,true);
        if(!empty($search)){
            if(isset($search["order_sn"])){
                $walletLogs=$walletLogs->where('(ext->\'$.order_sn\' like \'%'.$search["order_sn"][0].'%\' and  ext->\'$.order_type\' =\'order\') or ext->\'$.wallet_order_sn\' like \'%'.$search["order_sn"][0].'%\'');
            }
            if(isset($search["user_id"])){
                $walletLogs=$walletLogs->where(["user_id"=>$search["user_id"][0]]);
            }
            if(isset($search["createtime"])){
                $createtime = explode(' - ', $search["createtime"][0]);
                $walletLogs=$walletLogs->whereBetween('createtime', [strtotime($createtime[0]),strtotime($createtime[1])]);
            }
            if(isset($search["user.nickname"])){
                $walletLogs = WalletLogModel::with(["user"=>function($v) use ($search){
                    $v->whereLike("nickname","'%".$search["user.nickname"][0]."%'");
                }]);
                //$walletLogs=$walletLogs->whereLike("user.nickname","'%".$search["user.nickname"][0]."%'");
            }
            if(isset($search["user.mobile"])){
                $walletLogs = WalletLogModel::with(["user"=>function($v) use ($search){
                    $v->whereLike("mobile","'%".$search["user.mobile"][0]."%'");
                }]);
            }
        }
        $walletLogs=$walletLogs//->payment_goods()
            ->where("(type='payment_goods' and event='payment_goods_order_pay' and amount>0) 
            or (type='money' and (event in ('payment_goods_order_pay_income','payment_goods_order_pay_cost')) and memo like '%订单退货%' and amount<0)
            or (type='money' and event='payment_goods_order_pay_income'  and amount>0 and  memo like '%订单退货%')
            or (type='money' and event='order_refund' and amount>0)
            or (type='payment_goods' and event='money_cut_payment_order_pay' and amount<0)
            ")
            ->order("createtime desc,id desc")->paginate($list_rows);
        // 多态关联 oper
        $morphs = [
            'user' => \app\admin\model\shopro\user\User::class,
            'admin' => \app\admin\model\Admin::class,
            'system' => \app\admin\model\Admin::class,
        ];
        $walletLogs = morph_to($walletLogs, $morphs, ['oper_type', 'oper_id']);
        $walletLogs = $walletLogs->toArray();

        // 解析操作人信息
        foreach ($walletLogs['data'] as &$log) {
            $log['oper'] = Operator::info($log['oper_type'], $log['oper'] ?? null);
        }
        $this->success('', null, $walletLogs);
    }
    /**
     * 导出
     * */
    public function export()
    {
        $cellTitles = [
            // 订单表字段
            'id' => 'ID',
            'user.id' => '用户ID',
            'user.nickname' => '用户昵称',
            'amount' => '变动余额/货款',
            'before' => '变更前',
            'after' => '剩余余额/货款',
            'order_sn' => '订单编号',
            'oper.id' => '操作人ID',
            'oper.nickname' => '操作人昵称',
            'createtime' => '交易时间',
            'memo' => '备注',
        ];

        // 数据总条数
        $walletLogs = WalletLogModel::with("user");
        $search = $this->request->param("search");
        $search=json_decode($search,true);
        if(!empty($search)){
            if(isset($search["order_sn"])){
                $walletLogs=$walletLogs->where('(ext->\'$.order_sn\' like \'%'.$search["order_sn"][0].'%\' and  ext->\'$.order_type\' =\'order\') or ext->\'$.wallet_order_sn\' like \'%'.$search["order_sn"][0].'%\'');
            }
            if(isset($search["user_id"])){
                $walletLogs=$walletLogs->where(["user_id"=>$search["user_id"][0]]);
            }
            if(isset($search["createtime"])){
                $createtime = explode(' - ', $search["createtime"][0]);
                $walletLogs=$walletLogs->whereBetween('createtime', [strtotime($createtime[0]),strtotime($createtime[1])]);
            }
            if(isset($search["user.nickname"])){
                $walletLogs = WalletLogModel::with(["user"=>function($v) use ($search){
                    $v->whereLike("nickname","'%".$search["user.nickname"][0]."%'");
                }]);
                //$walletLogs=$walletLogs->whereLike("user.nickname","'%".$search["user.nickname"][0]."%'");
            }
            if(isset($search["user.mobile"])){
                $walletLogs = WalletLogModel::with(["user"=>function($v) use ($search){
                    $v->whereLike("mobile","'%".$search["user.mobile"][0]."%'");
                }]);
            }
        }
        $walletLogs=$walletLogs//->payment_goods()
        ->where("(type='payment_goods' and event='payment_goods_order_pay' and amount>0) 
            or (type='money' and (event in ('payment_goods_order_pay_income','payment_goods_order_pay_cost')) and memo like '%订单退货%' and amount<0)
            or (type='money' and event='payment_goods_order_pay_income'  and amount>0 and  memo like '%订单退货%')
            or (type='money' and event='order_refund' and amount>0)
            or (type='payment_goods' and event='money_cut_payment_order_pay' and amount<0)
            ");
        $total=$walletLogs->count();
        if ($total <= 0) {
            $this->error('导出数据为空');
        }

        $export = new \addons\shopro\library\Export();
        $params = [
            'file_name' => '退单明细列表',
            'cell_titles' => $cellTitles,
            'total' => $total,
            'is_sub_cell' => true,
            'sub_start_cell' => 'activity_type_text',
            'sub_field' => 'items'
        ];

        $result = $export->export($params, function ($pages) use (&$total_order_amount, &$total_pay_fee, &$total_real_pay_fee, &$total_discount_fee, &$total_score_amount, $total,$walletLogs) {
            $walletLogs = WalletLogModel::with("user");
            $search = $this->request->param("search");
            $search=json_decode($search,true);
            if(!empty($search)){
                if(isset($search["order_sn"])){
                    $walletLogs=$walletLogs->where('(ext->\'$.order_sn\' like \'%'.$search["order_sn"][0].'%\' and  ext->\'$.order_type\' =\'order\') or ext->\'$.wallet_order_sn\' like \'%'.$search["order_sn"][0].'%\'');
                }
                if(isset($search["user_id"])){
                    $walletLogs=$walletLogs->where(["user_id"=>$search["user_id"][0]]);
                }
                if(isset($search["createtime"])){
                    $createtime = explode(' - ', $search["createtime"][0]);
                    $walletLogs=$walletLogs->whereBetween('createtime', [strtotime($createtime[0]),strtotime($createtime[1])]);
                }
                if(isset($search["user.nickname"])){
                    $walletLogs = WalletLogModel::with(["user"=>function($v) use ($search){
                        $v->whereLike("nickname","'%".$search["user.nickname"][0]."%'");
                    }]);
                    //$walletLogs=$walletLogs->whereLike("user.nickname","'%".$search["user.nickname"][0]."%'");
                }
                if(isset($search["user.mobile"])){
                    $walletLogs = WalletLogModel::with(["user"=>function($v) use ($search){
                        $v->whereLike("mobile","'%".$search["user.mobile"][0]."%'");
                    }]);
                }
            }
            $datas=$walletLogs//->payment_goods()
            ->where("(type='payment_goods' and event='payment_goods_order_pay' and amount>0) 
            or (type='money' and (event in ('payment_goods_order_pay_income','payment_goods_order_pay_cost')) and memo like '%订单退货%' and amount<0)
            or (type='money' and event='payment_goods_order_pay_income'  and amount>0 and  memo like '%订单退货%')
            or (type='money' and event='order_refund' and amount>0)
            or (type='payment_goods' and event='money_cut_payment_order_pay' and amount<0)
            ")->order("createtime","desc")->limit((($pages['page'] - 1) * $pages['list_rows']), $pages['list_rows'])
                ->select();
            $datas = collection($datas);
            $newDatas = [];
            $goods_list="";
            $items = [];
            foreach ($datas as &$item) {
                $nickname="系统";
                if($item["oper_type"]=="user"){
                    //用户
                    $nickname=User::where(["id"=>$item["oper_id"]])->column("nickname")[0];
                }
                if($item["oper_type"]=="admin"){
                    //平台
                    $nickname=Admin::where(["id"=>$item["oper_id"]])->column("nickname")[0];
                }
                $data = [
                    // 订单表字段
                    'id' => $item['id'],
                    'user.nickname' =>$item["user"]["nickname"]??'',
                    'user.id' =>$item["user"]["id"]??0,
                    'amount' =>$item["amount"],
                    'before' =>$item["before"],
                    'after' =>$item["after"],
                    'order_sn' =>$item["ext"]["order_sn"]??($item["ext"]["wallet_order_sn"]??''),
                    'createtime' =>$item["createtime"],
                    'oper.id' =>$item["oper_id"],
                    'oper.nickname' =>$nickname,
                    'memo' =>$item["memo"],
                ];

                $data['items'] = $items;
                $data['goods_list'] = $goods_list;
                $newDatas[] = $data;
            }
            return $newDatas;
        });

        $this->success('导出成功' . (isset($result['file_path']) && $result['file_path'] ? '，请在服务器: “' . $result['file_path'] . '” 查看' : ''), null, $result);
    }
}
